import { FormSchema } from 'amis'
import apiObjectConfigPropsUtils from '@/components/utils/ApiObjectConfigPropsUtils'
import smsAppIdSelectUtils from '@/components/sms/smsAppIdSelectUtils'
import { SelectControlSchema } from 'amis/lib/renderers/Form/Select'
import { TextareaControlSchema } from 'amis/lib/renderers/Form/Textarea'

import { ApiObject, fetcherResult, Payload } from 'amis-core/lib/types'
import { HttpStatusCode } from 'axios'
import SmsBatchSendResponse from '@/core/sms/types/model/response/SmsBatchSendResponse'
import coreConstants, { SUCCESS_CODE } from '@/core/constants/coreConstants'
import smsAdminApiConfig from '@/core/sms/generated/apiconfig/smsAdminApiConfig'
import smsApiConfig from '@/core/sms/apiconfig/smsApiConfig'

// 立刻发送短信表单
class SmsSendFormUtils {
	getSchema = (): FormSchema => {
		return {
			type: 'form',
			api: apiObjectConfigPropsUtils.convert({
				apiConfig: smsApiConfig.smsBatchSend,
				adaptor: (payload: object, response: fetcherResult, api: ApiObject, context: any): any => {
					console.log(payload)
					if (response.status !== HttpStatusCode.Ok) {
						return payload
					}

					const payloadObjType = payload as Payload
					if (payloadObjType && payloadObjType.status === SUCCESS_CODE) {
						return payload
					}
					const dataResponse = payloadObjType.data as SmsBatchSendResponse
					if (dataResponse && Number(dataResponse.failureCount) > 0) {
						payloadObjType.msg = `成功:${dataResponse.successCount},失败:${dataResponse.successCount}`
					}
					return payloadObjType
				},
				requestAdaptor: (api: ApiObject, context: any): ApiObject | Promise<ApiObject> => {
					const smsList = [] as any[]
					if (context.phoneNumber) {
						const phoneNumberList = context.phoneNumber.split(',') as string[]
						if (phoneNumberList.length > 0) {
							smsList.push(
								...phoneNumberList.map(phoneNumber => {
									return {
										phoneNumber: phoneNumber,
										content: context.content,
									}
								}),
							)
						}
					}
					const newData: any = {
						smsAppId: context.smsAppId,
						smsList: smsList,
					}
					api.data = newData
					return api
				},
			}),
			body: [
				{
					...smsAppIdSelectUtils.getSchema(),
					required: true,
				} as SelectControlSchema,
				{
					type: 'textarea',
					name: 'phoneNumber',
					label: '手机号码',
					required: true,
					placeholder: '批量发送,手机号码以","分隔',
				} as TextareaControlSchema,
				{
					type: 'textarea',
					name: 'content',
					label: '短信内容',
					required: true,
					showCounter: true,
					maxLength: 200,
					placeholder: '超70个字符会拆分多条短信',
				} as TextareaControlSchema,
			],
		}
	}
}

export default new SmsSendFormUtils()
